/*
 *  Copyright (C) 2004 Cidero, Inc.
 *
 *  Permission is hereby granted to any person obtaining a copy of 
 *  this software to use, copy, modify, merge, publish, and distribute
 *  the software for any non-commercial purpose, subject to the
 *  following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included
 *  in all copies or substantial portions of the Software.
 *
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS 
 *  OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
 *  THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 *  LIABILITY IN CONNECTION WITH THE SOFTWARE.
 * 
 *  File: $RCSfile: BufferedReaderInputStream.java,v $
 *
 */

package com.cidero.util;

import java.io.IOException;
import java.io.InputStream;
import java.io.BufferedInputStream;

/**
 *  Class to add readLine() functionality to a BufferedInputStream.
 *  Useful when input consists of a mixture of text and binary data
 *  (e.g. HTTP requests/responses)
 */
public class BufferedReaderInputStream extends BufferedInputStream
{
  byte[] tmp;
  
  public BufferedReaderInputStream( InputStream inputStream )
  {
    super( inputStream );
    tmp = new byte[4096];
  }
  public BufferedReaderInputStream( InputStream inputStream, int maxLineSize )
  {
    super( inputStream );
    tmp = new byte[maxLineSize];
  }

  /**
   * Read a line of text.  A line is considered to be terminated by any one
   * of a line feed ('\n'), a carriage return ('\r'), or a carriage return
   * followed immediately by a linefeed.
   *
   * @return     A String containing the contents of the line, not including
   *             any line-termination characters, or null if the end of the
   *             stream has been reached
   *
   * @exception  IOException  If an I/O error occurs
   */
  public String readLine() throws IOException
  {
    int count = 0;
    
    while( true )
    {
      int b = read();
      
      if( b == -1 )
      {
        if( count == 0 )  // No characters at all for this line?
          return null;
      }
      else if( b == '\n' )
      {
        break;
      }
      else if( b != '\r' )
      {
        if( count >= tmp.length )
          throw new IOException("Max line length for reader obj exceeded");
        
        tmp[count++] = (byte)b;
      }
    }

    return new String( tmp, 0, count );
  }

  public void close() throws IOException
  {
    super.close();
    tmp = null;
  }
  
}
